<?php
declare(strict_types=1);

namespace Service\DeclareService\PayDeclareCompany;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Order;
use Service\VenderClient\PayCenterApi\HelipayApiClient;
use App\Model\BbcModel\OrderReportLog;
use App\Model\BbcModel\PayReport;
use App\Model\BbcModel\OrderReportStatus;
use Service\MessageService\PayNotifyService;
use Service\DeclareService\PayDeclareService;
use App\Model\BbcModel\OrderGoods;
use Service\GoodsService\ChannelGoodsService;

class Helipay extends BaseService
{
    public function reportPay(array $body):array {
        $reportOrder=$body['reportOrder'];
        $payconfig=$body['payconfig'];
        $company=$body['company'];
        $cid=$body['cid'];
        if(empty($reportOrder) || empty($payconfig) || empty($company)){
            return Normal::returnCode(Normal::SUC, '参数缺失,丢弃该条数据');
        }
        //获取回调
        if(isset($body['domain'])&&!empty($body['domain'])){
            $domain=$body['domain'];
            $noticeUrl="{$domain}/paydeclare/notify/hnapay";
        }else{
            $callback_url = PayNotifyService::instance()->getChannelNotifyHost($cid);
            $noticeUrl="http://{$callback_url}/paydeclare/notify/hnapay";
        }
        $receive_info=json_decode($reportOrder[0]['receive_info'],true);
        
        if(count($reportOrder)==1){
            $ordergoods= OrderGoods::instance()->lists(['order_id'=>$reportOrder[0]['id']]);
            $order_goods=[];
            $goodsIds= array_column($ordergoods, 'goods_id');
            $goodsList          = ChannelGoodsService::instance()->queryGoodsList($goodsIds);
            $goodsListMap       = array_column($goodsList,null,'id');
            foreach ($ordergoods as $key => $value) {
                $goodsmoney= bcsub($value['price_pay'], $value['price_tax'],2);
                $goodsItemAmount= bcdiv((string)$goodsmoney, (string)$value['num'],2);
                $goodsAmount= bcmul((string)$goodsItemAmount, (string)$value['num'],2);
                $order_goods[]=[
                    'goodsName'=>(string)$goodsListMap[$value['goods_id']]['name'],
                    'goodsNum'=>(string)$value['num'],
                    'goodsItemAmount'=>(float)$goodsItemAmount,//单价
                    'orderAmount'=>(float)$value['price_pay'],//支付金额
                    'freight'=>0.00,//运费
                    'goodsAmount'=>(float)$goodsAmount,//支付货款
                    'tax'=>(float)$value['price_tax'],//支付税款
                ];
            }
            $money= bcsub((string)$reportOrder[0]['price_order'], (string)$reportOrder[0]['points_money'],2);
            $body['pay_sn'] = $reportOrder[0]['sn'];
            $report_data=[
                'order_sn'=>(string)$body['pay_sn'],
                'money'=>(float)$money,
                'enterpriseNum'=>$company['eCompanyCode'],
                'enterpriseName'=>$company['eCompanyName'],
                'payDate'=>(string) date('Y-m-d H:i:s',$reportOrder[0]['pay_time']),
                'callbackUrl'=>$noticeUrl,
                'buyerName' =>$receive_info['buyer']['truename'],
                'buyerIdCardNo'=>$receive_info['buyer']['idcard'],
                'buyerPhone'=>$receive_info['buyer']['mobile'],
                'order_goods'=>$order_goods
            ];
            OrderReportLog::instance()->add([
                'order_id'=>$reportOrder[0]['id'],
                'sn'=>$body['pay_sn'],
                'content'=>"发起支付单申报",
                'cd'=>time()
            ]);
            
            $client = (new HelipayApiClient($payconfig));
            $result_call = $client->orderApplyCustom($report_data);
            PayReport::instance()->add([
                'order_id'=>$reportOrder[0]['id'],
                'sn'=>$body['pay_sn'],
                'content'=>json_encode($result_call,JSON_UNESCAPED_UNICODE)
            ]);
            if($result_call['code']==Normal::SUC){
                PayDeclareService::instance()->dealDeclareResult($body['pay_sn'], $reportOrder[0]['id'], '支付单申报成功');
                
                if($reportOrder[0]['need_order_report']==1){
                        //TODO订单申报
                    }
                
            }else{
                PayDeclareService::instance()->dealDeclareResult($body['pay_sn'], $reportOrder[0]['id'], '支付单申报失败:'.$result_call['msg'],false);
            }
        }else{
            //拆单申报
            $extendOrder=[];
            $orderSNs= array_column($reportOrder, 'sn');
            $OrderReportStatusList=OrderReportStatus::instance()->lists([['sn','in',$orderSNs]]);
            $OrderReportStatusMapList= array_column($OrderReportStatusList, Null,'sn');
            $subOrderExtends=[
                'OrderReportStatusMapList'  =>$OrderReportStatusMapList,
                'pay_serial_extend'         =>''
            ];
            foreach ($reportOrder as $v){
                OrderReportLog::instance()->add(['order_id'=>$v['id'],'sn'=>$v['sn'],'content'=>"发起支付单申报",'cd'=>time()]);
                OrderReportLog::instance()->add(['order_id'=>$v['id'],'sn'=>$v['sn'],'content'=>"暂不支持拆单申报",'cd'=>time()]);
                PayDeclareService::instance()->dealDeclareResult($v['sn'], $v['id'], '暂不支持拆单申报',false,$subOrderExtends);
            }
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
    
    public function notify(array $body) {
       //todo  合利宝，暂未开通回调
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
}
